package com.oauth2;

import com.oauth2.utils.HttpURLClient;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 第三方软件后端
 */
@WebServlet("/AppServlet")
public class AppServlet extends HttpServlet {

    // 授权服务
    String oauthURl="http://localhost:8081/OauthServlet";
    // 受保护资源服务
    String protectedURl="http://localhost:8081/ProtectedServlet";

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 一、授权码换取令牌
        String code = request.getParameter("code");

        Map<String, String> params = new HashMap<String, String>();
        params.put("code",code);
        params.put("grant_type","authorization_code");
        params.put("app_id","APPID_RABBIT");
        params.put("app_secret","APPSECRET_RABBIT");

        System.out.println("start post code for token ...");
        String accessToken = HttpURLClient.doPost(oauthURl,HttpURLClient.mapToStr(params));

        System.out.println("accessToken:"+accessToken);

        // 二、使用令牌
        Map<String, String> paramsMap = new HashMap<String, String>();

        paramsMap.put("app_id","APPID_RABBIT");
        paramsMap.put("app_secret","APPSECRET_RABBIT");
        paramsMap.put("token",accessToken);

        String result = HttpURLClient.doPost(protectedURl,HttpURLClient.mapToStr(paramsMap));
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
